#!/bin/bash
#shell script to automatically delete core and javacore files in system
#code mostly taken from skulker 1.31 bsh script (AIX)
#
#This script should be called from crontab once a week.

#first, the remove_file function -  
#Remove the file only if no process has it currently open
#not really using this function right now....
remove_file()
{
	if [ -z "`/sbin/fuser $1 2>/dev/null`" ]; then
	   /bin/rm -f $1 2>/dev/null
	fi
}

#skfile=/skulker.log
#date=`/bin/date`
#uname=`/bin/uname -nm`
#/bin/echo "$0 started at $date on $uname" >> $skfile


# Uncomment the NATIVE entry that is appropriate for your system.
# For Distributed environments, '/native' is a path to the local filesystems;
# '/' is sufficient for standalone systems.
# NATIVE=/native/
NATIVE=/

#clean out files in mail queues
if [ -d ${NATIVE}var/spool/mail ]
then
  for file in `/usr/bin/find ${NATIVE}var/spool/mail 2>/dev/null`
  do
	remove_file $file
  done
fi

#clean out old tracefiles that have been stored for 2 weeks or more
if [ -d ${NATIVE}var/ct/IW/log/mc ]
then
  for file in `/usr/bin/find ${NATIVE}var/ct/IW/log/mc -name trace.* -mtime +10 -type f 2>/dev/null`
  do 
     remove_file $file
  done
fi

# get rid of core files in any directory that are more than 2 weeks old, 
#javacore* files too.  Also dependent upon space.
# Other types of files may come later. 
#
# Use the -xdev flag to prevent find from traversing a filesystem
# on a different device, this will prevent it from searching nfs
# mounted filesystems.  You may want to add filesystems here
# that you want to be cleaned up.

#If there is no space left on a filesystem, then remove stuff immediately
for mntpoint in `/bin/df -l -m | /usr/bin/tail +2 | /bin/awk '{print $6}'`
do
#  echo `/bin/df "$mntpoint" -l -m | /usr/bin/tail +2 | /bin/awk '{print $4}'`
#  echo $mntpoint

  if [ `/bin/df "$mntpoint" -l -m | /usr/bin/tail +2 | /bin/awk '{print $4}'` -lt 500 ] 
  then
    for n in `/usr/bin/find $mntpoint -name core -o -name core.* -o -name javacore* -xdev -type f`
    do
	remove_file $n
    done
          
    if [ -e ${NATIVE}var/adm/wtmp -a "$mntpoint" = ${NATIVE}var ]
    then
      if [ `/usr/bin/du ${NATIVE}var/adm/wtmp | /bin/awk '{ print $1}'` -gt 0 ]
      then
        cat /dev/null > ${NATIVE}var/adm/wtmp
      fi
    fi 
#else, wait until cores and javacores are 2 weeks old to remove them
 else
    for n in `${NATIVE}usr/bin/find "$mntpoint" \( -name core -o -name core.* -o -name javacore* \) -xdev -atime +7 -mtime +14 -type f`
    do
	remove_file $n
    done
 fi
done

#date=`/bin/date`
#/bin/echo "$0 finished at $date on $uname" >> $skfile






